﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.ComponentModel;

namespace ClassicJukebox
{
    public sealed class RelayCommand : ICommand
    {
        private readonly Predicate<object> canExecuteMethod = null;
        private readonly Action<object> executeMethod = null;

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (this.canExecuteMethod != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (this.canExecuteMethod != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }

        public RelayCommand(Action<object> executeMethod)
            : this(executeMethod, null)
        {
        }

        public RelayCommand(Action<object> executeMethod, Predicate<object> canExecuteMethod)
        {
            if (executeMethod == null)
            {
                throw new ArgumentNullException("executeMethod", "Delegate comamnds can not be null");
            }

            this.executeMethod = executeMethod;
            this.canExecuteMethod = canExecuteMethod;
        }

        public bool CanExecute(object parameter)
        {
            if (this.canExecuteMethod == null)
            {
                return true;
            }
            else
            {
                return this.canExecuteMethod(parameter);
            }
        }

        public void Execute(object parameter)
        {
            if (this.executeMethod == null)
            {
                return;
            }
            else
            {
                this.executeMethod(parameter);
            }
        }
    }
} 
